package cn.qu.dockman.mgr.ws.exec;

import cn.qu.dockman.mgr.disparte.ArgDef;
import cn.qu.dockman.mgr.disparte.DispartMgr;
import cn.qu.dockman.mgr.entity.Host;
import cn.qu.dockman.mgr.entity.Image;
import cn.qu.dockman.mgr.service.HostService;
import cn.qu.dockman.mgr.service.ImageService;
import cn.qu.dockman.protocol.command.Command;
import cn.qu.dockman.protocol.command.client.ImageListCommand;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zh on 17/3/16.
 */
public class ImageListCommandParser extends CommandParser {

    private DispartMgr dispartMgr;
    private HostService hostService;
    private ImageService imageService;

    @Override
    public void before() {
        this.dispartMgr = getApplicationContext().getBean(DispartMgr.class);
        this.hostService = getApplicationContext().getBean(HostService.class);
        this.imageService = getApplicationContext().getBean(ImageService.class);
    }

    @Override
    public void parse(Command command) {

        ImageListCommand cmd = (ImageListCommand) command;

        Host host = hostService.findByIp(this.getHost());

        if(host == null) return;

        List<Image> imageList = imageService.findByHostId(host.getId());
        Map<String, Image> imageMap = new HashMap<>();
        imageList.forEach(image -> imageMap.put(image.getImageId(), image));

        ImageListCommand.ImageListBody[] bodys = cmd.getBody();

        for (ImageListCommand.ImageListBody body : bodys) {
            if (imageMap.containsKey(body.getId())) {
                imageMap.remove(body.getId());
            }
            ArgDef def = new ArgDef(ImageListCommand.NAME, this.getHost(), this.getPort(),this.getHostname());
            def.setData(body);

            dispartMgr.notifyObservers(def);
        }
        imageMap.forEach((key, value) -> imageService.delete(value));

    }
}
